/**
 * @Author: liu.yang
 * @Date: 2018-05-17 09:42:35
 */

import React, { Component } from "react";
import { Layout, Modal,ConfigProvider  } from "antd";
import zhCN from "antd/lib/locale-provider/zh_CN";
import { connect } from "dva";
import Cookies from "js-cookie";
import router from "umi/router";
import { isPhone } from "utils/comm";
import { TransitionGroup, CSSTransition } from "react-transition-group";
import TopHeader from "../header/TopHeader";
// import BottomFooter from "../footer/BottomFooter";
import menuData from "./menuData";
import BaseMenu from "../menu/BaseMenu";
import Exception from "../exception/Exception";
import LoadingPage from "./LoadingPage";
import lock from "../../assets/images/lock.png";
import styles from "./BaseLayout.less";

const { Content } = Layout;

const filter = ["/login"];
const phoneUrls = [
  "/embedded/phone/todo-detail",
  "/embedded/phone/todo-detail/form",
  "/embedded/phone/todo-detail/add-sign",
];
const flowChartFilter = [
  "/flowmanage/flowchart",
  "/flowmanage/flowconfigure/detail",
  "/flowmanage/formbuilder",
  "/embedded/todo-detail",
  "/embedded/apply-detail",
  "/embedded/new-apply",
  "/embedded/form",
  "/embedded/process-form",
  "/flow-phone/form",
  ...phoneUrls,
];

const noLayoutWrapperFilter = [
  "/embedded/new-apply",
  "/embedded/form",
  "/embedded/process-form",
  "/flow-phone/form",
  "/todo/templatepage",
  "/todo/templatepagenew",
  "/todo/flow-node-history",
  ...phoneUrls,
];

// 不介入4a的路由
const no4AFilter = ["/todo/flow-node-history", "/flowmanage/flowconfigure/detail"];
const leaveConfirm = ["/flowmanage/flowchart"];
const externalLink = ["/systemmanagement/swagger"];

@connect(({ Public, appListMenu, PageNotice, loading }) => ({
  Public,
  appListMenu,
  resourceList: Public.resourceList,
  loading,
  noticeData: PageNotice.noticeData,
  msgTypes: PageNotice.noticeTypes,
}))
class BaseLayout extends Component {
  state = {
    collapsed: false,
  };

  menuRouterItem = "";

  oldPathname = "";

  componentDidMount() {
    // const userId = Cookies.get("userId");
    // if (!(userId || window.location.pathname === "/login")) {
    //   router.push("/login");
    // }
    this.menuRouterItem = this.getMenuRouter();
    this.initData();
  }

  getMenuRouter = () => {
    const {
      location: { pathname = "" },
      Public,
    } = this.props;
    const { menuDataList } = Public;
    if (this.oldPathname === pathname) return this.menuRouterItem;
    this.oldPathname = pathname;
    const newArr = menuDataList.filter(ele => ele.link === pathname);
    if (newArr && newArr.length > 0) {
      return newArr;
    }
    return [];
  };

  initData = () => {
    const { location } = this.props;
    // console.log(location.pathname.indexOf('/exception/'));

    const { dispatch } = this.props;
    const is4AHidden = no4AFilter.some(item => item === location.pathname);
    dispatch({ type: "PageNotice/getNoticeType" });
    if (!is4AHidden) {
      dispatch({ type: "Public/get4AUser" }).then(res => {
        if (res.errCode === 0) {
          sessionStorage.setItem("USER_NAME", `${res.datas.displayName}`);
          sessionStorage.setItem("USER_ID", `${res.datas.code}`);
          sessionStorage.setItem("USER_CODE", `${res.datas.code}`);
          try {
            sessionStorage.setItem("USER_ORGNAME", `${res.datas.extentAttributes.orgList[0].orgName}`);
          }
          catch (err) {
            sessionStorage.setItem("USER_ORGNAME", "");
          }
          if (BUSINESS_MODE === "0") {
            this.initResourceList();
            // this.initAppList();
            if (location.pathname === "/flowmanage/flowconfigure/detail") {
              return;
            }
            this.initNoticeList();
          }
        }
        // sessionStorage.setItem("USER_NAME", "");
        // sessionStorage.setItem("USER_ID", "");
        // sessionStorage.setItem("USER_CODE", "");
        // sessionStorage.setItem("USER_ORGNAME", "");
      });
    } else {
      dispatch({ type: "Public/setLoadingend" })
    }
  };

  initAppList = () => {
    const { dispatch } = this.props;
    dispatch({ type: "appListMenu/getAppListAllData" }).then(() => {
      const { appListMenu } = this.props;
      const { appListAll } = appListMenu;
      if (appListAll.length === 0) return;
      const oldAppId = Cookies.get("APPID");
      let focusAppId = appListAll[0].id;
      let focusAppName = appListAll[0].name;
      if (oldAppId) {
        const focusApp = appListAll.filter(ele => {
          return `${ele.id}` === `${oldAppId}`;
        });
        if (focusApp && focusApp.length > 0) {
          focusAppId = focusApp[0].id;
          focusAppName = focusApp[0].name;
        }
      }
      Cookies.set("APPID", focusAppId);
      dispatch({
        type: "appListMenu/focusApp",
        payload: {
          id: focusAppId,
          name: focusAppName,
        },
      });
      // dispatch({ type: "appListMenu/getAppListData" });
    });
  };

  initResourceList = () => {
    const { dispatch } = this.props;
    dispatch({ type: "Public/getResourceListByUserCode" });
  };

  initNoticeList = () => {
    const { dispatch } = this.props;
    const params = { pageNum: 1, pageSize: 10, status: 0 };
    dispatch({ type: "PageNotice/getNoticeList", payload: params });
  };

  onCollapse = () => {
    const { collapsed } = this.state;
    this.setState({ collapsed: !collapsed });
  };

  onMenuItemClick = (e, link) => {
    // e.preventDefault();
    const {
      location: { pathname },
    } = this.props;
    if (leaveConfirm.includes(pathname)) {
      Modal.confirm({
        title: "您有未保存的更改",
        content: "您想如何处理未保存的更改？",
        cancelText: "放弃更改",
        okText: "继续编辑",
        onOk() {},
        onCancel() {
          router.push(link);
        },
      });
    } else if (!externalLink.includes(link)) {
      router.push(link);
    }
  };

  renderBaseLayout() {
    const {
      children,
      location,
      dispatch,
      Public,
      appListMenu,
      resourceList,
      noticeData,
      msgTypes,
      loading,
    } = this.props;
    const { collapsed } = this.state;
    const publicLoading = loading.models.Public;
    let newChildren = children;
    if (filter.some(item => item === location.pathname)) {
      return children;
    }
    if (publicLoading || publicLoading === undefined) {
      newChildren = <LoadingPage />;
    }
    this.menuRouterItem = this.getMenuRouter();

    if (
      !publicLoading &&
      location.pathname !== "/home" &&
      location.pathname !== "/todo/flow-node-history" &&
      location.pathname !== "/flowmanage/flowconfigure/detail" &&
      location.pathname !== "/" &&
      !menuData.some(ele => {
        return resourceList.some(element => element === ele.menuId);
      })
    ) {
      if (BUSINESS_MODE === "0") {
        // 如果只是打包业务系统访问的三个页面,不做权限控制提高访问速度
        // 页面权限
        newChildren = (
          <Exception title=" " desc="抱歉，你无权访问该页面" img={lock} />
        );
      }
    }
    /*
    if (Public.logout) {
      newChildren = <Exception title=' ' desc='抱歉，你无权访问该页面' img={lock} />;
    }
    */
    const filterHidden = flowChartFilter.some(
      item => item === location.pathname,
    );
    const layoutFilterHidden = noLayoutWrapperFilter.some(
      item => item === location.pathname,
    );
    // if (flowChartFilter.some(item => item === location.pathname)) {
    //   return <FlowChartLayout onMenuItemClick={this.onMenuItemClick} breadcrumbData={breadcrumbData}>{children}</FlowChartLayout>;
    // }

    return (
      <ConfigProvider locale={zhCN}>
        {!layoutFilterHidden ? (
          <Layout className={styles.root}>
            <BaseMenu
              collapsed={collapsed}
              data={menuData}
              onMenuItemClick={this.onMenuItemClick}
              className={`${filterHidden ? "ele__hidden" : ""}`}
              Public={Public}
              resourceList={resourceList}
            />
            <Layout>
              <div className={`${filterHidden ? "ele__hidden" : ""}`}>
                <TopHeader
                  collapsed={collapsed}
                  onCollapse={this.onCollapse}
                  dispatch={dispatch}
                  location={location}
                  data={menuData}
                  onMenuItemClick={this.onMenuItemClick}
                  appListMenu={appListMenu}
                  noticeData={noticeData}
                  msgTypes={msgTypes}
                />
              </div>
              {layoutFilterHidden ? null : (
                <Content className={styles.content}>{newChildren}</Content>
              )}
              {/* <BottomFooter /> */}
            </Layout>
          </Layout>
        ) : (
          newChildren
        )}
      </ConfigProvider>
    );
  }

  render() {
    const { location, history } = this.props;
    if (!isPhone()) {
      return this.renderBaseLayout();
    } else {
      return (
        <TransitionGroup
          style={{ height: "100%" }}
          className="phone-animation-group"
        >
          <CSSTransition
            key={location.pathname}
            classNames={history.action || ""}
            timeout={300}
          >
            {this.renderBaseLayout()}
          </CSSTransition>
        </TransitionGroup>
      );
    }
  }
}

export default BaseLayout;
